package com.fenxiangle.yueding.feature.home.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.fenxiangle.yueding.R;
import com.fenxiangle.yueding.common.util.RxKeyboardTool;
import com.fenxiangle.yueding.common.widget.citypicker.CityPickerActivity;
import com.fenxiangle.yueding.common.widget.citypicker.utils.StringUtils;
import com.fenxiangle.yueding.common.widget.dialog.ActionSheetDialog;
import com.fenxiangle.yueding.common.widget.dialog.BounceTopEnter;
import com.fenxiangle.yueding.common.widget.dialog.NormalDialog;
import com.fenxiangle.yueding.common.widget.dialog.OnBtnClickL;
import com.fenxiangle.yueding.common.widget.dialog.OnOperItemClickL;
import com.fenxiangle.yueding.common.widget.dialog.SlideBottomExit;
import com.fenxiangle.yueding.common.widget.popupwindow.FilterPopupWindow;
import com.fenxiangle.yueding.entity.bo.HomeDataBo;
import com.fenxiangle.yueding.entity.bo.PhotoBo;
import com.fenxiangle.yueding.entity.bo.UserCenterBo;
import com.fenxiangle.yueding.feature.home.contract.HomeContract;
import com.fenxiangle.yueding.feature.home.dependencies.home.DaggerHomeComponent;
import com.fenxiangle.yueding.feature.home.dependencies.home.HomePresenterModule;
import com.fenxiangle.yueding.feature.home.view.adapter.HomeAdapter;
import com.fenxiangle.yueding.feature.mine.view.ImageActivity;
import com.fenxiangle.yueding.feature.mine.view.VideoPlayerActivity;
import com.fenxiangle.yueding.feature.publish.view.PublishInviteActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.suozhang.framework.framework.AM;
import com.suozhang.framework.framework.BaseFragment;
import com.suozhang.framework.utils.logger.Logger;
import com.suozhang.framework.widget.EmptyView;
import com.suozhang.framework.widget.SpacesItemDecoration;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static android.app.Activity.RESULT_OK;
import static com.fenxiangle.yueding.common.widget.citypicker.CityPickerActivity.REQUEST_CODE_PICK_CITY;


public class HomeFragment extends BaseFragment implements HomeContract.View, OnRefreshListener,
        BaseQuickAdapter.OnItemChildClickListener, BaseQuickAdapter.RequestLoadMoreListener, OnOperItemClickL {

    @BindView(R.id.tv_home_city)
    TextView tvHomeCity;
    @BindView(R.id.rv_home)
    RecyclerView rvHome;
    @BindView(R.id.btn_home_filter)
    TextView btnHomeFilter;
    @BindView(R.id.smartRefesh)
    SmartRefreshLayout mSmartRefesh;
    Unbinder unbinder;
    @BindView(R.id.btn_select_type)
    TextView btnSelectType;
    @BindView(R.id.edt_search)
    EditText edtSearch;
    Unbinder unbinder2;

    private HomeAdapter mHomeAdapter;

    private String sortType;
    private String assess;
    private String city;
    private String sex;
    private String age;
    private EmptyView mEmptyView;
    private String authentication;
    private int mSearchType = 1;
    String[] stringItems = {"职业", "用户名", "用户ID"};
    int pageIndex = 1;
    int pageSize = 10;


    private List<HomeDataBo> mData;

    @Inject
    HomeContract.Presenter mPresenter;
    private ActionSheetDialog dialog;
    private AMapLocationClient mLocationClient;
    private NormalDialog normalDialog;




    @Override

    public int attachLayoutRes() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initInjector() {

        DaggerHomeComponent.builder().homePresenterModule(new HomePresenterModule(this)).build().inject(this);
    }


    @Override
    protected void initView() {
        RxKeyboardTool.hideSoftInput(getActivity());

        dialog = new ActionSheetDialog(getActivity(), stringItems, null);
        dialog.title("选择搜索条件");
        dialog.setOnOperItemClickL(this);
        dialog.titleBgColor(AM.res().getColor(R.color.primary_highlight));
        dialog.dividerColor(AM.res().getColor(R.color.text_secondary2));
        dialog.itemTextColor(AM.res().getColor(R.color.primary_comparison));
        dialog.lvBgColor(AM.res().getColor(R.color.primary_highlight));
        dialog.itemTextSize(15f);


        normalDialog = new NormalDialog(getActivity());
        normalDialog
                .title("定位失败")
                .content("是否手动选择?")//
                .showAnim(new BounceTopEnter())//
                .dismissAnim(new SlideBottomExit());
        normalDialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        try {
                            if (normalDialog != null) {
                                normalDialog.superDismiss();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        startActivityForResult(new Intent(getActivity(), CityPickerActivity.class),
                                REQUEST_CODE_PICK_CITY);
                    }
                });


        mSmartRefesh.setEnableLoadMore(false);
        mSmartRefesh.setOnRefreshListener(this);
        mEmptyView = new EmptyView(rvHome);
        rvHome.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        rvHome.addItemDecoration(new SpacesItemDecoration(2, 16, false));
        mHomeAdapter = new HomeAdapter();
        mHomeAdapter.bindToRecyclerView(rvHome);
        mHomeAdapter.setOnItemChildClickListener(this);
        mHomeAdapter.setOnLoadMoreListener(this, rvHome);
        mHomeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (TextUtils.isEmpty(mData.get(position).getUserVideoFormMap().getVideoUrl())) {
                    if (mData.get(position).getUserImagesFormMap() != null) {
                        List<PhotoBo> photoBos = new ArrayList<>();
                        photoBos.add(mData.get(position).getUserImagesFormMap());
                        Intent intent = new Intent(getActivity(), ImageActivity.class);
                        intent.putExtra("images", (Serializable) photoBos);
                        intent.putExtra("pos", 0);
                        startActivity(intent);
                    }
                } else {
                    HomeDataBo homeDataBo = mData.get(position);
                    UserCenterBo userCenterBo = new UserCenterBo();
                    userCenterBo.setFans(homeDataBo.getFans());
                    userCenterBo.setCreditScore(homeDataBo.getCreditScore());
                    userCenterBo.setTimeValue(homeDataBo.getTimeValue());

                    Intent intent = new Intent(getActivity(), VideoPlayerActivity.class);
                    intent.putExtra("userCenterBo", userCenterBo);
                    intent.putExtra("videoCoverImg", mData.get(position).getUserVideoFormMap().getVideoCover());
                    intent.putExtra("videoPath", mData.get(position).getUserVideoFormMap().getVideoUrl());
                    intent.putExtra("dec", mData.get(position).getUserVideoFormMap().getVideoDescribe());
                    startActivity(intent);
                }

            }
        });

    }

    @Override
    protected void initData() {
        pageIndex = 1;
        filterData();
    }

    @Override
    protected void initEvent() {
        initLocation();
        edtSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    pageIndex=1;
                    filterData();
                }
                return false;
            }
        });

        edtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
             if (TextUtils.isEmpty(s.toString())){
                 pageIndex=1;
                 filterData();
             }
            }
        });
    }


    @Override
    public void showHomeDataSuccess(List<HomeDataBo> s) {
        mSmartRefesh.finishRefresh();
        mData = s;
        setData(true, mData);

        mHomeAdapter.setEnableLoadMore(true);
    }

    @Override
    public void showHomeDataError(String error) {
        if (mSmartRefesh != null) mSmartRefesh.finishRefresh();
        mHomeAdapter.setEmptyView(mEmptyView.getErrorView(error));
        mHomeAdapter.setNewData(null);
        mHomeAdapter.setEnableLoadMore(true);
        mSmartRefesh.finishRefresh();
    }

    @Override
    public void showHomeDataMoreSuccess(List<HomeDataBo> msg) {
        setData(false, msg);
    }

    @Override
    public void showHomeDataMoreError(String msg) {
        mHomeAdapter.loadMoreFail();
    }

    private void setData(boolean isRefresh, List data) {
        pageIndex++;
        final int size = data == null ? 0 : data.size();
        if (isRefresh) {
            mHomeAdapter.setNewData(data);
        } else {
            if (size > 0) {
                mHomeAdapter.addData(data);
            }
        }
        if (size < pageSize) {
            //第一页如果不够一页就不显示没有更多数据布局
            mHomeAdapter.loadMoreEnd(isRefresh);
        } else {
            mHomeAdapter.loadMoreComplete();
        }
    }

    @Override
    public void showHomeDataEmpty() {
        mSmartRefesh.finishRefresh();
        mHomeAdapter.setEmptyView(mEmptyView.getEmptyView());
        mHomeAdapter.setNewData(null);
    }

    @Override
    public void showFollowSuccess() {
        showMsg("关注成功！");
        filterData();
        mSmartRefesh.autoRefresh();
    }

    @Override
    public void showUnFollowSuccess() {
        showMsg("已取消关注！");
        filterData();
        mSmartRefesh.autoRefresh();
    }

    @Override
    public void showFollowError(String error) {
        showMsg(error);
    }

    private void filterData() {
        mPresenter.getHomeData(pageIndex, pageSize,
                TextUtils.isEmpty(sortType) ? null : sortType,
                TextUtils.isEmpty(assess) ? null : assess,
                TextUtils.isEmpty(city) ? null : city,
                TextUtils.isEmpty(sex) ? null : sex,
                TextUtils.isEmpty(age) ? null : age,
                TextUtils.isEmpty(authentication) ? null : authentication
                , mSearchType, TextUtils.isEmpty(edtSearch.getText().toString())?null:edtSearch.getText().toString()
        );
    }


    @OnClick({R.id.tv_home_city, R.id.btn_home_filter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_home_city:
                startActivityForResult(new Intent(getActivity(), CityPickerActivity.class),
                        REQUEST_CODE_PICK_CITY);

                break;
            case R.id.btn_home_filter:
                FilterPopupWindow filterPopupWindow = new FilterPopupWindow(getActivity());
                filterPopupWindow.initPopupWindow(btnHomeFilter, new FilterPopupWindow.FilterCallBack() {
                    @Override
                    public void Filter(FilterPopupWindow.FilterInfo filterInfo) {
                        sortType = filterInfo.sortType;
                        sex = filterInfo.sex;
                        age = filterInfo.age;
                        authentication = filterInfo.authentication;
                        initData();
                    }
                });
                break;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_CITY && resultCode == RESULT_OK) {
            if (data != null) {
                String citys = data.getStringExtra(CityPickerActivity.KEY_PICKED_CITY);

                if (!TextUtils.isEmpty(citys)) {
                    tvHomeCity.setText(citys);
                }
            }
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refresh();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

        switch (view.getId()) {
            case R.id.iv_show_foucs:
            case R.id.btn_home_focus:
                Intent intent = new Intent(new Intent(getActivity(), PublishInviteActivity.class));
                intent.putExtra("uid", mData.get(position).getUserUid());
                startActivity(intent);
                break;
            case R.id.iv_home_head:
                Intent intents = new Intent(getActivity(), UserInfoActivity.class);
                intents.putExtra("id", mData.get(position).getUserUid());
                startActivity(intents);
                break;
        }

    }


    @Override
    public void onLoadMoreRequested() {
        loadMore();
    }


    private void refresh() {
        mHomeAdapter.setEnableLoadMore(false);
        initData();
    }

    private void loadMore() {
        mPresenter.getHomeMoreData(pageIndex, pageSize, TextUtils.isEmpty(sortType) ? null : sortType,
                TextUtils.isEmpty(assess) ? null : assess,
                TextUtils.isEmpty(city) ? null : city,
                TextUtils.isEmpty(sex) ? null : sex,
                TextUtils.isEmpty(age) ? null : age,
                TextUtils.isEmpty(authentication) ? null : authentication, mSearchType,TextUtils.isEmpty(edtSearch.getText().toString())?null:edtSearch.getText().toString());
    }

    @OnClick(R.id.btn_select_type)
    public void onViewClicked() {
        dialog.show();
    }

    @Override
    public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
        btnSelectType.setText(stringItems[position]);
        mSearchType = position + 1;
        dialog.dismiss();
    }

    private void initLocation() {
        mLocationClient = new AMapLocationClient(getActivity());
        AMapLocationClientOption option = new AMapLocationClientOption();
        option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        option.setOnceLocation(true);
        mLocationClient.setLocationOption(option);
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation != null) {
                    if (aMapLocation.getErrorCode() == 0) {
                        String city = aMapLocation.getCity();
                        String district = aMapLocation.getDistrict();
                        String location = StringUtils.extractLocation(city, district);
                        tvHomeCity.setText(location);
                        Logger.e("tag------>"+aMapLocation.getCityCode());
                    } else {
//                        normalDialog.show();
                    }
                }
            }

        });
        mLocationClient.startLocation();
    }

}
